package ms.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import ms.jasim.model.Decomposition;
import ms.jasim.model.Goal;
import ms.jasim.model.JasimModel;
import ms.jasim.model.impl.DecompositionImpl;

import org.eclipse.emf.ecore.util.EcoreUtil;

public class JasimUtils {
	
	@SuppressWarnings("unchecked")
	public static <T extends Serializable> T cloneObject(T obj) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
        try {
        	ObjectOutputStream out = new ObjectOutputStream(bos);
			out.writeObject(obj);
			out.close();
			ObjectInputStream inputStream = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
			return (T) inputStream.readObject();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static JasimModel cloneModel(JasimModel source) {
		JasimModel result = (JasimModel) EcoreUtil.copy(source);
		for (Goal g: result.getGoals()) {
			Goal sg = source.getGoals().get(g.getName());
			if (sg != null) {
				g.getDecomposition().clear();
				for (Decomposition sde: sg.getDecomposition()) {
					Decomposition de = new DecompositionImpl();
					for (Goal ssg: sde.getSubGoals()) {
						Goal g_sg = result.getGoals().get(ssg.getName());
						if (g_sg != null)
							de.getSubGoals().add(g_sg);
					}
					g.getDecomposition().add(de);
				}
			}
		}
		result.getPostProcessCommand().addAll(source.getPostProcessCommand());
		return result;
	}
}
